/*
 * @Author: sonss
 * @Date: 2024-09-03 18:43:49
 * @LastEditTime: 2024-09-03 20:57:16
 * @FilePath: /ss-file-antd/src/pages/Assets/Share/modules/Create.tsx
 * @Description:  资源分享
 */
import { Create } from '@/services/assets_share';
import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
import dayjs from 'dayjs';
import { useState } from 'react';

type CreateModuleProps = {
  params?: ASSETS.FILE.SearchParams;
  onClose?: () => void;
  onSuccess?: (data?: ASSETS.SHARE.CreateResponse) => void;
};

type CreateFieldsValue = {
  days?: number;
  shapwd?: string;
};

const CreateModule: React.FC<CreateModuleProps> = (props) => {
  const [form] = ProForm.useForm<CreateFieldsValue>();
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  const finish = async (values: CreateFieldsValue) => {
    const req: ASSETS.SHARE.CreateForm = {
      params: props.params || {},
      shapwd: values.shapwd,
    };

    if (values.days && values.days > 0) {
      req.expiredTime = dayjs().add(values.days, 'day').unix();
    }

    setConfirmLoading(true);
    Create(req)
      .then((res) => {
        if (res.code !== 0) {
          return;
        }

        if (props.onSuccess) {
          props.onSuccess(res.data);
        }
      })
      .finally(() => {
        setConfirmLoading(false);
      });
  };

  const handleOpenChange = (val: boolean) => {
    if (val) {
      return;
    }
    form.resetFields();

    if (props.onClose) {
      props.onClose();
    }
  };

  return (
    <>
      <ModalForm
        title="链接分享"
        form={form}
        modalProps={{
          destroyOnClose: true,
        }}
        open={true}
        onOpenChange={handleOpenChange}
        onFinish={finish}
        width="50%"
        submitter={{
          searchConfig: {
            submitText: '创建链接',
          },
          submitButtonProps: {
            loading: confirmLoading,
          },
        }}
      >
        <ProFormRadio.Group
          name="days"
          label="有效期"
          options={[
            {
              label: '1天',
              value: 1,
            },
            {
              label: '7天',
              value: 7,
            },
            {
              label: '30天',
              value: 30,
            },
            {
              label: '永久有效',
              value: 0,
            },
          ]}
          initialValue={0}
        />
        <ProFormText
          name="shapwd"
          width="sm"
          label="提取码"
          tooltip="若留空，则系统自动生成。"
          placeholder="请输入4位字母数字"
          rules={[{ pattern: /^[a-zA-z0-9]{4}$/, message: '只允许4为字母数字' }]}
        />
      </ModalForm>
    </>
  );
};

export default CreateModule;
